#include "thread.hpp"
#include "mutex"

#define ticket_max 1000;
int ticket = ticket_max;

//定义互斥锁
pthread_mutex_t mutex;
void* buy_ticket(void* arg)
{
    while(1)
    {
        //加锁
        pthread_mutex_lock(&mutex);
        if (ticket > 0)
        {
            usleep(500);
            ticket--;   
            std::cout << "抢票成功！剩余票数：" << ticket << std::endl;
            usleep(500);
            //解锁
            pthread_mutex_unlock(&mutex);
        }

        else
        {
            //解锁
            pthread_mutex_unlock(&mutex);
            std::cout << "没票了！" << std::endl;
            break;
        }
    }
    return nullptr;
}


int main()
{
    //初始化互斥锁
    pthread_mutex_init(&mutex, nullptr);

    //创建三个线程
    Thread t1(buy_ticket), t2(buy_ticket), t3(buy_ticket);

    //启动线程
    t1.thread_start();
    t2.thread_start();
    t3.thread_start();

    //等待线程
    t1.thread_join();
    t2.thread_join();
    t3.thread_join();

    //销毁锁
    pthread_mutex_destroy(&mutex);
    return 0;
}